import cv2
import numpy as np
import os
import random
from concurrent.futures import ProcessPoolExecutor
from tqdm.auto import tqdm
from datetime import datetime

# 图片文件夹路径
image_folder_path = r'd:\pdf'

# 视频文件所在的文件夹路径
video_folder_path = r'd:\pdf'

# 输出视频文件夹路径
output_folder_path = r'd:\pdf'

# 确保输出文件夹存在
os.makedirs(output_folder_path, exist_ok=True)

# 获取图片文件夹中所有图片文件的列表，并随机选择一张图片
image_files = [f for f in os.listdir(image_folder_path) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
if not image_files:
    print("图片文件夹中未找到图片。")
    exit()

random_image_file = random.choice(image_files)
random_image_path = os.path.join(image_folder_path, random_image_file)
print(f"选定用于叠加的图片：{random_image_file}")

# 打印代码开始执行的时间
start_time = datetime.now()
print(f"代码开始执行时间：{start_time.strftime('%Y-%m-%d %H:%M:%S')}")


# 定义处理视频的函数
def process_video(video_file, random_image_path, video_folder, output_folder):
    # 构建完整的视频和图片路径
    video_path = os.path.join(video_folder, video_file)
    output_video_path = os.path.join(output_folder, video_file)

    # 尝试打开视频文件
    cap = cv2.VideoCapture("d:\\pdf\\a1.mp4")
    if not cap.isOpened():
        print(f"视频打开失败：{video_path}")
        return

    # 获取视频的帧率和尺寸
    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # 读取图片，并确保以 np.uint8 类型读取
    image = cv2.imread(random_image_path, cv2.IMREAD_UNCHANGED)
    if image is None:
        print(f"图片加载失败：{random_image_path}")
        return

    # 将图片转换为 np.uint8 类型，如果需要的话
    if image.dtype != np.uint8:
        image = image.astype(np.uint8)

    # 将图片缩放到视频帧的尺寸
    image = cv2.resize(image, (frame_width, frame_height), interpolation=cv2.INTER_AREA)

    # 创建视频写入对象
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height), isColor=True)

    # 设置图片的透明度
    alpha = 0.0  # 根据需要调整透明度

    # 处理视频的每一帧
    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # 将图片以半透明的方式叠加到视频帧上
        frame = cv2.addWeighted(frame, 1, image, alpha, 0)

        # 将处理后的帧写入输出视频
        out.write(frame)

    # 释放资源
    cap.release()
    out.release()
    print(f"完成处理 {video_file}")


# 使用多进程执行视频处理
if __name__ == "__main__":
    with ProcessPoolExecutor(max_workers=4) as executor:  # 可以根据CPU核心数调整工作进程数
        futures = []
        for video_file in os.listdir(video_folder_path):
            if video_file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
                futures.append(executor.submit(process_video, video_file, random_image_path, video_folder_path,
                                               output_folder_path))

        # 使用tqdm显示整体进度
        for future in tqdm(futures, total=len(futures), desc="Overall Progress", unit="video"):
            try:
                future.result()  # 等待任务完成
            except Exception as e:
                print(f"视频处理出现错误：{e}")

    # 打印代码结束执行的时间并计算总耗时
    end_time = datetime.now()
    print(f"代码结束执行时间：{end_time.strftime('%Y-%m-%d %H:%M:%S')}")
    total_time = end_time - start_time
    hours, remainder = divmod(total_time.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    print(f"总耗时时长：{hours}时{minutes}分{seconds}秒")

    print("所有视频处理完成。")
